<template>
  <div>
    <!-- 成绩查询 -->
    <el-card style="margin-bottom:10px;padding:0;position:relative;">
      <span class="hint">输入框为空时，点击查询，可回到默认样式</span>
      <el-form :inline="true" ref="form" :model="findStudent" label-width="80px">
        <el-form-item label="学生查询">
          <el-input style="width:200px;" size="medium" v-model="findStudent.findName"></el-input>
          <el-button size="medium" style="margin-left:10px;" type="primary" icon="el-icon-search" @click="findStudentNameBtn">查询</el-button>
        </el-form-item>
         <el-form-item label="课程" label-width="140px">
          <el-select v-model="findStudent.subject" placeholder="活动区域" size="medium">
            <el-option :label="subject[0].toUpperCase() + subject.substr(1) " :value="subject" v-for="(subject,index) in subjectAndScore" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" label-width="50px">
          <el-select v-model="findStudent.score" placeholder="活动区域" size="medium">
            <el-option label="<60" value="60"></el-option>
            <!-- <el-option label="≥60" value="59"></el-option> -->
            <el-option label="60 ~ 80" value="60,79"></el-option>
            <el-option label="81 ~ 100" value="80,100"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="(!findStudent.subject || !findStudent.score)" size="medium" type="primary" @click="findSubJectAndScoreBtn">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 学生成绩信息 -->
    <el-card v-if="pageFlag">
      <!-- 头部 -->
      <div slot="header">
        <span style="position:absolute;left:50%;font-size:20px;">学生成绩信息</span>
        <div>
          <el-button type="primary" size="medium" @click="addScore">添加成绩</el-button>
          <el-button type="danger" size="medium" @click="batchDeleteScore">批量删除</el-button>
        </div>
        
      </div>
      <!-- 成绩信息内容 -->
      <div>
        <!-- default-sort: 默认排序 -->
        <el-table stripe :default-sort = "{prop: 'scoreId', order: 'ascending'}" border @selection-change="handleSelectionChange" :data="scoreList" style="width: 100%">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column sortable prop="scoreId" label="序号" width="80" align="center"></el-table-column>
          <el-table-column align="center" prop="studentName" label="姓名"></el-table-column>
          <el-table-column sortable align="center" prop="ps" label="Ps"></el-table-column>
          <el-table-column sortable align="center" prop="ai" label="Ai"></el-table-column>
          <el-table-column sortable align="center" prop="ae" label="Ae"></el-table-column>
          <el-table-column sortable align="center" prop="html_css" label="Html_Css" width="150"></el-table-column>
          <el-table-column sortable align="center" prop="javascript" label="JavaScript" width="150"></el-table-column>
          <el-table-column sortable align="center" prop="node" label="Node"></el-table-column>
          <el-table-column sortable align="center" prop="vue" label="Vue"></el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="{row}">
              <el-button style="margin-right:10px;" type="warning" title="修改成绩" icon="el-icon-edit" size="mini" @click="updateScore(row)"></el-button>
              <el-popconfirm :title="`确定删除${row.studentName}吗？`" @confirm="deleteScore(row)">
                <el-button title="删除成绩" slot="reference" type="danger" icon="el-icon-delete" size="mini" ></el-button>
              </el-popconfirm>
              
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加和修改成绩 -->
    <div v-else>
      <el-card>
      <div slot="header" style="font-size:20px;">添加学生成绩</div>
      <div>
        <el-form ref="scoreForm" :rules="scoreRules" :model="scoreInfo" label-width="80px">
          <el-row :gutter="10">
            <el-col :span="9">
              <el-form-item prop="studentName" label="姓名">
                <el-input  v-model="scoreInfo.studentName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item prop="ps" label="PS">
                <el-input v-model="scoreInfo.ps"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="9">
              <el-form-item prop="ai" label="Ai">
                <el-input v-model="scoreInfo.ai"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item prop="ae" label="Ae">
                <el-input v-model="scoreInfo.ae"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="9">
              <el-form-item prop="html_css" label="Html_Css">
                <el-input v-model="scoreInfo.html_css"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item prop="javascript" label="JavaScript">
                <el-input v-model="scoreInfo.javascript"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="9">
              <el-form-item prop="node" label="Node">
                <el-input v-model="scoreInfo.node"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item prop="vue" label="Vue">
                <el-input v-model="scoreInfo.vue"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="warning" @click="cancelBtn">取消</el-button>
            <el-button type="primary" @click="submitAddOrUpdateScore">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
      </el-card>
    </div>
    <!-- 分页器 -->
    <el-pagination
      style="text-align:center; margin-top:5px;"
      @size-change="handleSizeChange"
      @current-change="getStudentScore"
      :current-page="pagination.currentPage"
      :page-sizes="[3,5,7]"
      :page-size="pagination.limit"
      layout=" prev, pager, next, jumper, ->, total, sizes"
      :total="pagination.total"
      background
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: "studentScore",
  data() {
    // 校验分数
    const checkScore = (rule, value, callback) => {      
      let reg = /^\d{1,3}$/
      if(value > 100){
        callback(new Error('请输入正确的分数'))
      }else{
        reg.test(value) ? callback() : callback(new Error('请输入数值'))
      }
    }
    return {
      // 查询信息
      findStudent: {
        findName: "",
        subject: "",
        score: ""
      },
      // 成绩信息列表
      scoreList: [],
      // 成绩信息
      scoreInfo: {
        studentName: "",
        ps: "",
        ai: "",
        ae: "",
        html_css: "",
        javascript: "",
        node: "",
        vue: ""
      },
      // 校验表单
      scoreRules:{
        studentName:[
          {required:true,message:'请输入姓名',trigger:'blur'}
        ],
        ps:[
          {required:true,message:'请输入Ps成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        ai:[
          {required:true,message:'请输入Ai成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        ae:[
          {required:true,message:'请输入Ae成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        html_css:[
          {required:true,message:'请输入Html_Css成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        javascript:[
          {required:true,message:'请输入JavaScript成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        node:[
          {required:true,message:'请输入Node成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ],
        vue:[
          {required:true,message:'请输入Vue成绩',trigger:'blur'},
          {validator:checkScore,trigger:'blur'}
        ]
      },
      // 分页器
      pagination: {
        currentPage: 1, // 当前页
        limit: 5, // 页面展示数量
        total: undefined // 总数量
      },
      // 控制页面展示内容
      pageFlag: true,
      // 被选中成绩信息
      checkScoreList:[],
      // 控制数据加载种的提示显示
    };
  },
  mounted() {
    this.getStudentScore();
  },
  methods: {
    // 获取初始化学生成绩信息
    async getStudentScore(pager = 1) {
      this.pagination.currentPage = parseInt(pager);
      const loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        // 获取分页查询后学生成绩信息
        let result = await this.$store.dispatch(
          "studentScore/getFindPageStudentScore",
          this.pagination
        );
        let { currentPage, limit, total } = result;
        if (result.code === 200) {
          this.scoreList = result.data;
          this.pagination.currentPage = currentPage;
          this.pagination.limit = limit;
          this.pagination.total = total;
          loading.close()
        }
      } catch (error) {
        loading.close()
        this.$message.error(`*_*,${error.message}`);
      }
    },
    // 根据姓名查找成绩
    async findStudentNameBtn(){
      if(this.findStudent.findName === ''){
        this.getStudentScore()
        this.$message.success('初始化成功')
        return false
      }
      try {
        let result = await this.$store.dispatch('studentScore/getFindStudentName', this.findStudent.findName);
        if(result.code === 200){
          this.$message.success('^_^,加载成功')
          this.scoreList = result.data
        }
      } catch (error) {
        this.$message.error(`*_*,${error.message}`)
      }
    },
    // 根据课程和分数查询
    async findSubJectAndScoreBtn(){
      let result = await this.$store.dispatch('studentScore/getFindStudentSubjectScore', this.findStudent);
      if(result.code === 200){
        this.$message.success('^_^,加载成功')
        this.scoreList = result.data
      }
    },
    // 页面数量展示事件
    handleSizeChange(limit) {
      this.pagination.limit = limit;
      this.getStudentScore()
    },
    // 成绩选中状态
    handleSelectionChange(rows){
      this.checkScoreList = rows
    },
    // 添加成绩
    addScore() {
      this.pageFlag = false
      // 每次添加添加按钮时 先清空里面所有内容
      Object.assign(this._data.scoreInfo,this.$options.data().scoreInfo)
    },
    // 修改成绩
    updateScore(row) {
      this.scoreInfo = row
      this.pageFlag = false
    },
    // 删除学生
    async deleteScore(row) {
      let result = await this.$store.dispatch('studentScore/getDeleteStudentScore', row.scoreId);
      if(result.code === 200){
        this.$message.success('删除成功')
      }
      this.getStudentScore()
    },
    // 批量删除成绩
    batchDeleteScore() {
      let scoreIdArr = this.checkScoreList.map(item => {
        return item.scoreId
      })
      this.$store.dispatch('studentScore/getBatchDeleteStudentScore', scoreIdArr);
    },
    // 取消按钮
    cancelBtn(){
      this.pageFlag = true
    },
    // 确定按钮
    submitAddOrUpdateScore(){
      this.$refs.scoreForm.validate(async isTrue => {
        if(isTrue){
          try {
            let result = await this.$store.dispatch('studentScore/getAddOrUpdateStudentScore', this.scoreInfo);
            if(result.code === 200){
              this.$message.success(`${this.scoreInfo.scoreId?'修改成功':'添加成功'}`)
              this.getStudentScore()
              this.pageFlag = true
            }
          } catch (error) {
            this.$message.error(`${error.message}`)
          }
        }else{
          return false
        }
      })
    },
  },
  computed:{
    subjectAndScore(){
      let newArr = []
      for (const key in this.scoreInfo) {
        newArr.push(key)
      }
      return newArr.splice(1)
    }
  }
};
</script>

<style lang="less" scoped>
// 查询框提示
.hint{
  color:#999;
  font-size:12px;
  position:absolute;
  left:90px;
  top:2px;
}
.el-input{
  width: 300px;
}
/deep/ .el-card__body{
  padding: 20px 20px 0 20px !important;
}
</style>